﻿/*
 *FileName:      AsncReactivePropertySample.cs
 *Author:        changyou
 *Date:          2023/10/08 15:21:17
 *UnityVersion:  2021.3.15f1c1
 *Description:    更新血条显示
*/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using Cysharp.Threading.Tasks;
using Cysharp.Threading.Tasks.Linq;
// using RtsFlame;
using TMPro;
// using Unity.XR.OpenVR;
using UnityEngine;
using UnityEngine.UI;

public class AsncHaemalStrand : MonoBehaviour
{
    public bool isKindling;
    private AsyncReactiveProperty<float> currentHp;
    private float maxHp ;
    private float totalChangeTime = 1f;

    public Slider HpSlider;
    
    public TextMeshProUGUI currentHpText;//当前剩余温度Text值

    private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
    private CancellationTokenSource _linkedTokenSource;

    [SerializeField]
    private GameObject FireObj;

    private Camera main_Camera;

    private void Start()
    {
        // if (MyEngineAPIHandler.isInEditor)
        //     gameObject.SetActive(false);
    }

    public void Init(float Max_Hp)
    {
        maxHp = Max_Hp;
        HpSlider.maxValue = maxHp;
        if (currentHp == null)
        {
            // 如果 currentHp 尚未初始化，则进行初始 并监听 血量变化
            currentHp = new AsyncReactiveProperty<float>(maxHp);
            currentHp.Subscribe(OnHpChange);
        }
        else
        {
            // 如果已经初始化，则更新当前血量为新的最大值
            HpSlider.value = maxHp;
        }

        UpdateHpText(maxHp);
      
        if (_linkedTokenSource == null)
        {
            _linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token, this.GetCancellationTokenOnDestroy());
        }

        if (main_Camera == null)
        {
            main_Camera = Camera.main;
        }
    }

    private void Update()
    {
        transform.rotation = Quaternion.LookRotation(main_Camera.transform.forward);
    }

    public void ChangeHp(float deltaHp)
    {
        currentHp.Value = Mathf.Clamp(currentHp.Value + deltaHp, 0, maxHp);
        UpdateHpText(currentHp.Value);
    }

    private void UpdateHpText(float hp)
    {
        if (currentHpText != null)
            currentHpText.text = hp + "/" + maxHp;
    }

    private async UniTaskVoid OnHpChange(float hp)
    {
        try
        {
            CancelAndRenewToken();
            await SyncSlider(hp, _linkedTokenSource.Token);
        }
        catch (Exception e)
        {
            Debug.LogError("血条改变 错误: " + e.Message);
        }
    }

    private void CancelAndRenewToken()
    {
        _cancellationTokenSource.Cancel();
        _cancellationTokenSource.Dispose();
        _cancellationTokenSource = new CancellationTokenSource();
        _linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token, this.GetCancellationTokenOnDestroy());
    }

    private async UniTask SyncSlider(float hp, CancellationToken token)
    {
        var sliderValue = HpSlider.value;
        float needTime = Mathf.Abs((sliderValue - hp) / maxHp * totalChangeTime);
        float useTime = 0;

        while (useTime < needTime)
        {
            useTime += Time.deltaTime;
            try
            {
                await UniTask.Yield(PlayerLoopTiming.Update, token);
            }
            catch (OperationCanceledException)
            {
                // 处理异步操作的取消
                return;
            }

            var newValue = (sliderValue + (hp - sliderValue) * (useTime / needTime));
            SetNewValue(newValue);
        }
    }

    private void SetNewValue(float newValue)
    {
        if (!HpSlider) return;

        HpSlider.value = newValue;
        HandleHpDepletion();
    }

    private void HandleHpDepletion()
    {
        if (HpSlider.value <= 0)
        {
            // Implement logic for when HP is depleted
            ProcessFireObjectDeactivation();
        }
    }

    private void ProcessFireObjectDeactivation()
    {
        // FlameCore f = FireObj.GetComponentInParent<FlameCore>();
        // if (f != null)
        // {
        //     DisableHpSlider();
        //     f.ShutDownFire();
        // }
        // else
        // {
            FireObj.SetActive(false);
        // }
    }

    private void DisableHpSlider()
    {
        HpSlider.maxValue = 0;
        HpSlider.value = 0;
        if (isKindling)
        { 
            transform.root.gameObject.SetActive(false);
        }
        else
        {
            HpSlider.gameObject.SetActive(false);
        }
        
        transform.root.tag = "Untagged";
    }
    
}
